﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myTwitter.BO;
using myTwitter.API;
using myTwitter.Model;
using System.Net;
using myBoard.Framework;
using myBoard.Framework.BO;
using System.Reflection;
using System.Windows.Media.Animation;
using myBoard.Framework.Security;

namespace myTwitter
{
	/// <summary>
	/// Interaction logic for LoginScreen.xaml
	/// </summary>
	public partial class LoginScreen
	{
        public delegate void SuccessfullyLoggedInHandler(User loginUser);
        public event SuccessfullyLoggedInHandler SuccessfullyLoggedIn;
        private Storyboard _showLoginSB;
        private Storyboard _showOAuthenSB;
        private User _loggedUser;

		public LoginScreen()
		{
			this.InitializeComponent();
            _signInBt.Click += new RoutedEventHandler(_signInBt_Click);
            _loginTbx.KeyUp += new KeyEventHandler(_loginTbx_KeyUp);
            _passwordTbx.KeyUp += new KeyEventHandler(_passwordTbx_KeyUp);
            _getAuthorizationCodeBt.Click += new RoutedEventHandler(_getAuthorizationCodeBt_Click);
            _authorizeBt.Click += new RoutedEventHandler(_authorizeBt_Click);
            _showLoginSB = this.Resources["ShowLogin"] as Storyboard;
            _showOAuthenSB = this.Resources["ShowAuthentBlock"] as Storyboard;
            this.Loaded += new RoutedEventHandler(LoginScreen_Loaded);
            InitTwitterProvider();            
		}

        void LoginScreen_Loaded(object sender, RoutedEventArgs e)
        {
            this.BeginStoryboard(_showLoginSB);
        }        

        void _getAuthorizationCodeBt_Click(object sender, RoutedEventArgs e)
        {
            GlobalController.Instances.ITwitterProvider.GetAuthorizationCode();
        }

        void _authorizeBt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UserOAuthenSettings userOAuthenSettings = GlobalController.Instances.ITwitterProvider.Authorize(_authorizationCodeTbx.Text);
                GlobalController.Settings.MagnetSettings.UsersOAuthenSettings.Add(userOAuthenSettings);
                LoadHomeScreen();
            }
            catch (Exception ex)
            {
                ExceptionsManager.LogException("Sinapse", ex, true);
                return;
            }            
        }        

        void _loginTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                _signInBt_Click(sender, null);
        }

        void _passwordTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                _signInBt_Click(sender, null);
        }

        void _signInBt_Click(object sender, RoutedEventArgs e)
        {
            _loginTbx.IsEnabled = false;
            _passwordTbx.IsEnabled = false;
            GlobalController.Instances.ITwitterProvider.Login = _loginTbx.Text;
            GlobalController.Instances.ITwitterProvider.Password = _passwordTbx.Password;
            
            UserOAuthenSettings currentUserOAuthenSettings = null;
            foreach (UserOAuthenSettings userOAuthenSettings in GlobalController.Settings.MagnetSettings.UsersOAuthenSettings)
            {
                if (userOAuthenSettings.Login == _loginTbx.Text)
                {
                    currentUserOAuthenSettings = userOAuthenSettings;
                    break;
                }
            }
            if (currentUserOAuthenSettings == null)
            {
                this.BeginStoryboard(_showOAuthenSB);
            }
            else
            {
                GlobalController.Instances.ITwitterProvider.CurrentUserOAuthenSettings = currentUserOAuthenSettings;
                GlobalController.Instances.ITwitterProvider.VerifyCredential();
                _preLoader.Start();
            }            
        }

        private void InitTwitterProvider()
        {
            if (myTwitter.GlobalController.Settings.DemoMode)
                GlobalController.Instances.ITwitterProvider = new Test_TwitterProvider();
            else
                GlobalController.Instances.ITwitterProvider = new TwitterProvider();
            
            GlobalController.Instances.ITwitterProvider.VerifyCredentialCompleted += new VerifyCredentialCompletedHandler(ITwitterProvider_VerifyCredentialCompleted);
        }

        void ITwitterProvider_VerifyCredentialCompleted(User user)
        {
            _preLoader.Stop();
            _loginTbx.IsEnabled = true;
            _passwordTbx.IsEnabled = true;

            if (user == null)
            {
                Exception ex = GlobalController.Instances.ITwitterProvider.LastException;
                if (ex is WebException &&
                    ((WebException)ex).Response is HttpWebResponse &&
                    ((HttpWebResponse)((WebException)ex).Response).StatusCode == HttpStatusCode.Unauthorized)
                {
                    ExceptionsManager.Write("myTwitter", "Authentification failed", "Wrong Username/Email and password combination.",
                        System.Diagnostics.EventLogEntryType.Warning, true);
                }
                else
                {
                    ExceptionsManager.LogException("myTwitter", ex, true);
                }
            }
            else
            {
                foreach (UserOAuthenSettings userOAuthenSettings in GlobalController.Settings.MagnetSettings.UsersOAuthenSettings)
                {
                    if (userOAuthenSettings.Login == _loginTbx.Text)
                    {
                        userOAuthenSettings.Password = Encryption.Encrypt(_passwordTbx.Password);
                        break;
                    }
                }
                _loggedUser = user;
                LoadHomeScreen();
            }
        }

        private void LoadHomeScreen()
        {
            GlobalController.Settings.IsConnected = true;
                GlobalController.Views.Navigator.SyncWithTwitterProvider();
                GlobalController.Instances.Twitter.SyncWithTwitterProvider();

                if (SuccessfullyLoggedIn != null)
                    SuccessfullyLoggedIn(_loggedUser);
        }
	}
}